package com.app.controller;

import com.app.common.Result;
import com.app.model.*;
import com.app.server.*;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.vo.DisasterHandleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 野生动物救助处理
 */
@Slf4j
@RestController
@RequestMapping("/sbbz/rescueHandle")
public class RescueHandleController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private RescueHandService rescueHandService;

    @Autowired
    private AnimalRescueService animalRescueService;

    @Autowired
    private RecordFileService recordFileService;
    @Autowired
    private UnitsManagerService unitsManagerService;

    // 查询动物救助处理
    @GetMapping("/getRescueHandle")
    public Result getHandleList(@RequestParam(defaultValue = "0") Integer page,
                                @RequestParam(defaultValue = "10") Integer limit, Integer rescueId) {

        QueryWrapper<RescueHandleModel> qw = new QueryWrapper<>();
        qw.eq("rescue_id", rescueId);
        RescueHandleModel rescueHandle = rescueHandService.getOne(qw);
        return Result.success(rescueHandle);
    }

    //根据id查询
    @GetMapping("/getHandleById")
    public Result getHandleById(Integer id) {
        RescueHandleModel rescueHandle = rescueHandService.getById(id);
        return Result.success(rescueHandle);
    }

    // 新增和修改
    @PostMapping("/addAndUpdateHandle")
    public Result addAndUpdateHandle(@RequestBody RescueHandleModel rescueHandleModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.parseInt(adminId));
        if (adminUser == null) {
            return Result.error(406, "用户不存在");
        }
        //新增和修改野生动物处理
        Result<String> stringResult = rescueHandService.addAndUpdateHandle(rescueHandleModel);
        //处理完成后 更改状态
        AnimalRescueModel animalRescue = animalRescueService.getById(rescueHandleModel.getRescueId());
        animalRescue.setAllocationStatus(3);
        animalRescue.setHandleStatus(2);
        if (adminUser.getUnitsId() != null) {
            UnitsManagerModel byId = unitsManagerService.getById(adminUser.getUnitsId());
            if (byId != null) {
                animalRescue.setRealName(byId.getName());
            }
        }
        animalRescueService.updateById(animalRescue);
        return stringResult;
    }
}
